#include "window.h"
#include "client.h"
#include <pthread.h>
#include <signal.h>

client::Client * clit;
client::Window * wind;
//可以利用单例模式进行构造对象

  void * Send_Entry(void * arg)
  {
    (void)arg;
   while(true)
   {
      wind->Input_Win();
      std::string msg;
      //从输入窗口中获取到用户输入的字符串
      wind->Get_String_From_Win(wind->_input_win,msg);
      clit->Send_Msg(msg);
      wind->Input_Win();
   }
   return NULL;
  }

  void * Recv_Entry(void * arg)
  {
    (void)arg;
    while(true)
    {
      wind->Message_Win();
      wind->Online_List_Win();
      //先从服务器端接收数据
      server::Msg msg;

      clit->Recv_Msg(msg);
      if(msg.cmd == "quit")
      {
        wind->Del_Friend(msg.name,msg.gender,msg.age);
      }
      else
      {
        wind->Add_Friend(msg.name,msg.gender,msg.age);
        //客户端将消息放入消息队列
        wind->Add_Msg(msg.name,msg.words);
      }
    }
    return NULL;
  }


  //信号处理函数
  void  Clear(int sig)
  {
    (void)sig; 
    delete clit;
    delete wind;
    exit(1);
  }


  int main(int argc,char * argv[])
  {
    //注册信号捕捉函数
    signal(SIGINT,Clear);


    //验证命令行参数是否正确
    if(argc != 3)
    {
      printf("Usage ./client [ip]  [port]\n");
      return 1;
    }

    //初始化window 设置
    
    clit = new client::Client;
    //1.初始化用户端信息
    clit->Init_Client(argv[1],atoi(argv[2]));
    //2.设置用户信息
    std::string name;
    std::string gender;
    std::string age;
    std::cout<<"请输入姓名：";
    std::cin >> name;
    std::cout<<"请输入性别：";
    std::cin >> gender;
    std::cout<<"请输入年龄：";
    std::cin>> age;
    clit->Set_Client_Info(name,gender,age);

    wind = new client::Window;
    wind->Header_Win();

    //3.创建两个线程一个用来发送消息，一个用来接收消息
    pthread_t send_pid ;
    pthread_t recv_pid;
    pthread_create(&send_pid,NULL,Send_Entry,NULL);
    pthread_create(&recv_pid,NULL,Recv_Entry,NULL);


    //4.进行线程等待，回收资源
    pthread_join(send_pid,NULL);
    pthread_join(recv_pid,NULL);
    //5.进行后序清理工作

    return 0;
  }

